package com.phil.test;

import com.google.gdata.client.douban.DoubanService;
import com.phil.util.Constants;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class OAuthDialog extends Dialog {

	public static final int FETCH_URL_HANDLER_SUCCUSS = 1;
	public static final int FETCH_URL_HANDLER_FAIL = FETCH_URL_HANDLER_SUCCUSS + 1;
	DoubanService myService;
	static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.FILL_PARENT);
	private ProgressDialog mSpinner;
	private WebView mWebView;
	private LinearLayout mContent;
	private TextView mTitle;
	static final int MARGIN = 4;
	static final int PADDING = 2;
	static final int FB_BLUE = 0xFF6D84B4;
	static final float[] DIMENSIONS_LANDSCAPE = { 550, 300 };
	static final float[] DIMENSIONS_PORTRAIT = { 300, 550 };
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FETCH_URL_HANDLER_SUCCUSS:
				String url = (String) msg.obj;
				Log.v("---------", "url == " + url);
				setUpWebView(url);
				break;
			case FETCH_URL_HANDLER_FAIL:
				break;
			default:
				break;
			}

		}
	};

	public OAuthDialog(Context context) {
		super(context);
		mSpinner = new ProgressDialog(getContext());
		mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mSpinner.setMessage(getContext().getString(R.string.loading));

		mContent = new LinearLayout(getContext());
		mContent.setOrientation(LinearLayout.VERTICAL);

		setUpTitle();
		Display display = getWindow().getWindowManager().getDefaultDisplay();
		final float scale = getContext().getResources().getDisplayMetrics().density;
		float[] dimensions = display.getWidth() < display.getHeight() ? DIMENSIONS_PORTRAIT
				: DIMENSIONS_LANDSCAPE;
		addContentView(mContent, new FrameLayout.LayoutParams(
				(int) (dimensions[0] * scale + 0.5f), (int) (dimensions[1]
						* scale + 0.5f)));
		myService = new DoubanService("subApplication", Constants.APLKEY,
				Constants.APISECRET);
		new FetchRequestUrlThead().start();
	}

	private void setUpTitle() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		mTitle = new TextView(getContext());
		mTitle.setText(getContext().getString(R.string.douban));
		mTitle.setTextColor(Color.WHITE);
		mTitle.setTypeface(Typeface.DEFAULT_BOLD);
		mTitle.setBackgroundColor(FB_BLUE);
		mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
		mTitle.setCompoundDrawablePadding(MARGIN + PADDING);

		mContent.addView(mTitle);
	}

	private void setUpWebView(String mUrl) {
		mWebView = new WebView(getContext());
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.setWebViewClient(new OAuthWebViewClient());
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setSavePassword(false);
		mWebView.loadUrl(mUrl);

		mWebView.setLayoutParams(FILL);
		mContent.addView(mWebView);
	}

	private class OAuthWebViewClient extends WebViewClient {
		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			Log.v("test", "finish url = " + url);

		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {

		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			Log.v("shouldOverrideUrlLoading", "url == " + url);
			getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url))); 
			return false;

		}

	}

	private String getURL() throws Exception {
		// don't need network
		// clearCookies(context);

		myService.setReadTimeout(25 * 1000);
		String url = myService.getAuthorizationUrl(Constants.REQUEST_TOKEN_URL);
		// Log.v("--------", "url:" + url);
		// Log.v("--------", "requestSecret" +
		// myService.getRequestTokenSecret());
		// String requestToken = myService.getRequestToken();
		// Log.v("-----------", "requestToken == " + requestToken);

		return url;
	}

	class FetchRequestUrlThead extends Thread {
		@Override
		public void run() {

			try {
				String url = getURL();
				Message msg = new Message();
				msg.obj = url;
				msg.what = FETCH_URL_HANDLER_SUCCUSS;
				handler.sendMessage(msg);
			} catch (Exception e) {
				Message msg = new Message();
				msg.what = FETCH_URL_HANDLER_FAIL;
				handler.sendMessage(msg);
				e.printStackTrace();
			}

		}
	}
}
